package com.credit.mola.app.ui.process.activity

import android.net.Uri
import android.view.View
import androidx.camera.core.AspectRatio
import androidx.camera.core.CameraSelector
import androidx.camera.core.ImageCapture
import androidx.camera.core.ImageCaptureException
import androidx.camera.core.Preview
import androidx.camera.lifecycle.ProcessCameraProvider
import androidx.core.content.ContextCompat
import com.credit.mola.app.app.App
import com.credit.mola.app.databinding.ActivityCameraFaceBinding
import com.credit.mola.app.pro.ProActivity
import com.credit.mola.app.utils.BarUtils
import com.credit.mola.app.utils.DensityUtils
import com.credit.mola.app.utils.event.EventType
import com.credit.mola.app.utils.gilde.ImageUtil
import com.credit.mola.app.utils.http.AppUrls
import com.credit.mola.app.utils.http.IHttpCallback
import com.credit.mola.app.utils.imagecovert.ImageConvert
import com.credit.mola.app.utils.log.HHLog
import org.json.JSONObject
import java.io.File
import java.util.concurrent.ExecutorService
import java.util.concurrent.Executors

/**
 * Sikadwa
 * @Author wwdeng
 * @CreateTime: 2024/5/29 18:06
 * @Annotation：人脸拍照
 */
class CameraFaceActivity: ProActivity() {
    private var _binding: ActivityCameraFaceBinding? = null
    private val binding get() = _binding ?: throw IllegalStateException(
        "Cannot Face camera binding because it is null. Either the view hasn't been created yet, or it has already been destroyed."
    )

    private lateinit var cameraExecutor: ExecutorService
    private var imageCapture: ImageCapture? = null
    private var imgUri: Uri? = null
    private var imgUsePath = ""
    override fun getRootView(): View {
        _binding = ActivityCameraFaceBinding.inflate(layoutInflater)
        return binding.root
    }

    override fun initView() {
        BarUtils.setStatusBarLightMode(this, false)
        _binding?.titleLayout?.setPadding(0,BarUtils.getStatusBarHeight(),0,0)

        cameraExecutor = Executors.newSingleThreadExecutor()
        initFaceCameraViewScale()
        startCamera()
    }

    override fun initListener() {
        _binding?.imgBack?.setOnClickListener {
            finish()
        }

        _binding?.imgKefu?.setOnClickListener {
            showKefuDialog("FaceCamera Page")
            addEvent(EventType.CLICK.CLICK_CUSTOMER,"FaceCamera Page")
        }

        //拍照
        _binding?.imgTakeCamera?.setOnClickListener {
            addEvent(EventType.CLICK.CLICK_CAMERA_TAKE_PHOTO,"FaceCamera Page")
            takeFilePhoto()
        }

        //重拍
        _binding?.remakeLayout?.setOnClickListener {
            addEvent(EventType.CLICK.CLICK_STEP_FACE_REMAKE,"")
            showTakeView()
        }

        //使用
        _binding?.usePhotoLayout?.setOnClickListener {
            addEvent(EventType.CLICK.CLICK_STEP_FACE_USE_PHOTO, imgUsePath)
            showLoading()
            // 图片处理
            ImageConvert.covert(context = this, uri = imgUri) { localPath, bitmap ->
                if (localPath != null){
                    HHLog.e("imageConvert success>>>>>>>$localPath")
                    uploadImageAction(localPath)
                }
            }
        }
    }

    override fun initData() {
    }

    /**
     * 打开相机预览
     */
    private fun startCamera() {
        showTakeView()
        val cameraProviderFuture = ProcessCameraProvider.getInstance(this)
        cameraProviderFuture.addListener(Runnable {
            val cameraProvider: ProcessCameraProvider = cameraProviderFuture.get()
            val preview = Preview.Builder()
                .setTargetAspectRatio(AspectRatio.RATIO_4_3)
                .build()
                .also {
                    it.setSurfaceProvider(_binding?.cameraView?.surfaceProvider)
                }
            imageCapture = ImageCapture.Builder().build()
            //打开前置摄像头
            val cameraSelector = CameraSelector.DEFAULT_FRONT_CAMERA
            try {
                cameraProvider.unbindAll()
                cameraProvider.bindToLifecycle(this, cameraSelector, preview,imageCapture)
            } catch(exc: Exception) {
            }
        }, ContextCompat.getMainExecutor(this))
    }

    /**
     * 设置相机画面和拍照预览View的宽高和位置
     */
    private fun initFaceCameraViewScale(){
        // 确保 PreviewView 的布局参数设置为 4:3
        _binding?.cameraView?.post {
            val width = App.app.getPhoneWidth() - DensityUtils.dp2px(100f)
            val layoutParams = _binding?.cameraView?.layoutParams
            layoutParams?.width = width
            layoutParams?.height = width
            _binding?.cameraView?.layoutParams = layoutParams

            _binding?.cameraView?.y = ((App.app.getPhoneHeight() - width) / 3).toFloat()
        }

        _binding?.imgPreview?.post {
            val width = App.app.getPhoneWidth() - DensityUtils.dp2px(100f)
            val layoutParams = _binding?.imgPreview?.layoutParams
            layoutParams?.width = width
            layoutParams?.height = width
            _binding?.imgPreview?.layoutParams = layoutParams

            _binding?.imgPreview?.y = ((App.app.getPhoneHeight() - width) / 3).toFloat()
        }
    }

    /**
     * 拍照并保存到本地
     */
    private fun takeFilePhoto(){
        if (imageCapture != null){
            //创建文件
            val filePath = App.instance().filesDir.absolutePath
            val outputFile = File(filePath,"${System.currentTimeMillis()}.jpg")
            if (!outputFile.exists()){
                outputFile.mkdir()
            }
            //创建输出选项对象
            val metadata = ImageCapture.Metadata().apply {
                // 当为前置摄像头时镜像；前置摄像头预览时默认就是镜像
                isReversedHorizontal = true
            }
            //创建文件
            val outputFileOptions = ImageCapture.OutputFileOptions.Builder(outputFile).setMetadata(metadata).build()
            //开始拍照
            imageCapture?.takePicture(outputFileOptions,ContextCompat.getMainExecutor(this),object : ImageCapture.OnImageSavedCallback{
                override fun onImageSaved(outputFileResults: ImageCapture.OutputFileResults) {
                    imgUri = outputFileResults.savedUri
                    imgUri?.path?.let {
                        HHLog.e("take photo complete>>>>>>>${it}")
                        imgUsePath = it
                        ImageUtil.instance?.loadImageUrl(this@CameraFaceActivity,_binding?.imgPreview,imgUsePath,0)
                    }
                    showCompleteView()
                }
                override fun onError(exception: ImageCaptureException) {
                    HHLog.e("take photo failed >>>>>>>${exception.message}")
                }
            })
        }
    }

    /**
     * 显示拍照样式
     */
    private fun showTakeView(){
        _binding?.let { binding ->
            binding.imgPreview.visibility = View.GONE
            binding.imgTakeCamera.visibility = View.VISIBLE
            binding.remakeLayout.visibility = View.INVISIBLE
            binding.usePhotoLayout.visibility = View.INVISIBLE
        }
    }

    /**
     * 显示拍照完成页面
     */
    private fun showCompleteView(){
        _binding?.let { binding ->
            binding.imgPreview.visibility = View.VISIBLE
            binding.imgTakeCamera.visibility = View.INVISIBLE
            binding.remakeLayout.visibility = View.VISIBLE
            binding.usePhotoLayout.visibility = View.VISIBLE
        }
    }

    /**
     * 上传图片
     */
    private fun uploadImageAction(imgPath: String){
        val httpUrl = AppUrls.getHttpUrl(AppUrls.URL.FILE)
        uploadFileAction(httpUrl,File(imgPath),object : IHttpCallback {
            override fun onRequestSuccess(data: JSONObject) {
                hideLoading()
                val obj = data.optJSONObject("obj")
                obj?.let {
                    val imgUrl = obj.optString("url")
                    val intent = intent
                    intent.putExtra("imgLocalPath",imgUsePath)
                    intent.putExtra("imgUrl",imgUrl)
                    setResult(RESULT_OK,intent)
                    finish()
                }
            }

            override fun onRequestError(error: JSONObject) {
            }

            override fun onRequestFinish() {
                hideLoading()
            }
        })
    }

    override fun onStart() {
        super.onStart()
        addEvent(EventType.PAGE.PAGE_STEP_FACE_CAMERA_START,"")
    }

    override fun onDestroy() {
        super.onDestroy()
        _binding = null
        addEvent(EventType.PAGE.PAGE_STEP_FACE_CAMERA_END,"")
        if (::cameraExecutor.isInitialized){
            cameraExecutor.shutdown()
        }
    }
}